package udp.host.test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.util.Log;

public class Server implements Runnable {

	public static final String SERVERIP = "127.0.0.1"; // 'Within' the emulator!
	public static final int SERVERPORT = 4444;
	public InetAddress CLIENTIP; // 'Within' the emulator!
	public int CLIENTPORT = 4444;
	public DatagramSocket hostSocket;

	@Override
	public void run() {
		try {
			/* Retrieve the ServerName */
			InetAddress serverAddr = InetAddress.getByName(SERVERIP);

			Log.d("UDP", "S: Connecting...");
			/* Create new UDP-Socket */
			DatagramSocket hostSocket = new DatagramSocket(SERVERPORT,
					serverAddr);

			/* By magic we know, how much data will be waiting for us */
			byte[] buf = new byte[81];
			/*
			 * Prepare a UDP-Packet that can contain the data we want to receive
			 */
			DatagramPacket packet = new DatagramPacket(buf, buf.length);

			/* Receive the UDP-Packet */
			for (int i = 0; i < 10; i++) {

				Log.d("UDP", "S: Receiving...");
				hostSocket.receive(packet);
				CLIENTIP = packet.getAddress();
				CLIENTPORT = packet.getPort();
				Log.d("UDP", "S: Received: '" + new String(packet.getData())
						+ "'");
				buf = ("360000000004230800000004200" +
						"070460003820000014500013020" +
						"001900000007048300000000000").getBytes();
				packet = new DatagramPacket(buf, buf.length, CLIENTIP,
						CLIENTPORT);
				Log.d("UDP", "S: Sending packet...");
				synchronized (this) {
					  this.wait(500);
					}
				hostSocket.send(packet);
				Log.d("UDP", "S: Done.");
			}
			hostSocket.close();
		} catch (Exception e) {
			Log.e("UDP", "S: Error", e);
		}

	}
}